package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryTodayBest(Long toUserId) {
//        db.recommend_user.find({toUserId:1}).sort({"score":-1}).limit(1)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        query.limit(1);
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override //分页查询推荐的佳人
    public PageResult queryRecommendation(Long toUserId, Integer page, Integer pagesize) {
//        db.recommend_user.find({toUserId:1}).sort({"score":-1}).limit(pagesize).skip((page-1)*pagesize+1)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        query.limit(pagesize);
        query.skip((page-1)*pagesize+1);
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageResult(page,pagesize,(int)count,recommendUserList);
    }

    @Override
    public Long queryScore(Long toUserId, Long userId) {
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser==null){
            return RandomUtils.nextLong(70,90);
        }
        return recommendUser.getScore().longValue();
    }

    @Override
    public void delete(Long toUserId, Long userId) {
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        mongoTemplate.remove(query,RecommendUser.class);
    }
}
